import { login, getInfo, getDetailUser } from '@/api/user'
import { getToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    // 从本地cookie取得初始值
    token: getToken(),
    info: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    getUserInfo(state, info) {
      state.info = info
    },
    clearToken(state) {
      state.token = ''
    },
    clearInfo(state) {
      state.info = {}
    }
  },
  actions: {
    // 登录拿到token
    async getUser(context, data) {
      const res = await login(data)
      context.commit('setToken', res.data.data)
    },
    // 个人信息
    async getInfo(context) {
      const res = await getInfo()
      const id = res.data.data.userId
      const res1 = await getDetailUser(id)
      context.commit('getUserInfo', { ...res.data.data, ...res1.data.data })
    },
    // 退出登录
    logout(context) {
      context.commit('clearToken')
      context.commit('clearInfo')
    }
  }
}

